package it.unibo.deis.lia.mmhc.test;

import it.unibo.deis.lia.mmhc.mpe.MobilityEstimator;

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;

public class MPETestApplet extends Applet implements ActionListener {

	private JLabel CMob, State;
	private JButton buttonStart;
	private JButton buttonStop;
	private DataUpdater dataUpdater = null;

	public void init() {
		setLayout(new BorderLayout(1, 2));
		setBackground(Color.lightGray);

		buttonStart = new JButton("Start MPE");
		buttonStop = new JButton("Stop MPE");
		buttonStart.addActionListener(this);
		buttonStop.addActionListener(this);

		CMob = new JLabel("CMob");
		State = new JLabel("State");

		add("North", CMob);
		add("South", State);
		add("West", buttonStart);
		add("East", buttonStop);

		this.setSize(200, 75);
	}

	public void start() {
		System.out.println("Applet starting.");
	}

	public void stop() {
		System.out.println("Applet stopping.");
	}

	public void destroy() {
		System.out.println("Destroy method called.");
	}

	public void actionPerformed(ActionEvent event) {
		// Object source = event.getSource();
		String actionCommand = event.getActionCommand();
		System.out.println("actionCommand: " + actionCommand);
		if (actionCommand.equals("Start MPE")) {
			try {
				if (dataUpdater != null) {
					dataUpdater.stopDataUpdater();
				}
				dataUpdater = new DataUpdater(CMob, State);
				dataUpdater.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			if (dataUpdater != null) {
				dataUpdater.stopDataUpdater();
			}
			dataUpdater = null;
		}
	}

	private class DataUpdater extends Thread {

		private boolean ok = true;
		// private MobilityEstimator mobilityEstimator;
		private JLabel CMob, State;

		public DataUpdater(JLabel CMob, JLabel State) throws Exception {
			this.CMob = CMob;
			this.State = State;
		}

		public void run() {
			try {
				// mobilityEstimator=new
				// MobilityEstimator/*IEEE80211*/(/*250,*/0,-1/*,0*/);
				MobilityEstimator mobilityEstimator = MobilityEstimator
						.getInstance(/*
									 * MobilityEstimator.StandardDevice,MobilityEstimator
									 * .UNUSED
									 */);
				// mobilityEstimator.startMobilityEstimator();
				Thread.sleep(1000);
				while (ok) {
					CMob.setText("CMob: "
							+ mobilityEstimator.getMobilityDegree());
					if (mobilityEstimator.getMobilityState() == MobilityEstimator.STILL) {
						State.setText("State: Still");
					} else if (mobilityEstimator.getMobilityState() == MobilityEstimator.MOTION) {
						State.setText("State: Motion");
					} else {
						State.setText("State: NotAvailable");
					}
					Thread.sleep(500);
				}
				mobilityEstimator.stopMobilityEstimator();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void stopDataUpdater() {
			ok = false;
		}
	}
}
